var express = require('express');
var router = express.Router();
const UsersModel = require('../../models/UsersModel');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const secret = require('../../config/config');

router.post('/login', (req, res) => {
    let {username, password} = req.body;
    UsersModel.findOne({username: username, password: md5(password)}, (error, data) => {
        if (error) {
            res.status(500);
            res.json({
                code: '2001',
                msg: '数据库连接失败',
                data:null
            });
            return;
        }
        if (!data) {
            res.json({
                code:'2002',
                msg:'账号或密码错误',
                data:null
            });
            return;
        }
        req.session.username = data.username;
        req.session._id = data._id;
        let token = jwt.sign(
            {username: data.username, _id: data._id, password: data.password},
            secret,
            {expiresIn: 60 * 60 * 24 * 7}
        );
        res.json(
            {
                code: '0000',
                msg:'登陆成功',
                token:token
            }
        );
    })
});

//为了方式跨域的攻击
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '退出成功', url: '/login'})
    });
});

module.exports = router;
